﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

/**
 * @file PrefabList
 * 
 * @author LeonXie
 * */

namespace Catsland.Core {
    /**
     * @brief the list of prefabs
     * 
     * prefab is actually gameObject. but it is seemed as the template of gameObject.
     * prefab is distinguished by name(unique), while gameObject is by guid
     * */
    public class PrefabList : UniqueList<GameObject> {
        public override void AddItem(string key, GameObject value) {
            base.AddItem(key, value);
            if (Mgr<GameEngine>.Singleton._gameEngineMode == GameEngine.GameEngineMode.MapEditor) {
                Mgr<GameEngine>.Singleton.Editor.UpdatePrefabList(this);
            }
        }

        public override void RemoveItem(string key) {
            base.RemoveItem(key);
            if (Mgr<GameEngine>.Singleton._gameEngineMode == GameEngine.GameEngineMode.MapEditor) {
                Mgr<GameEngine>.Singleton.Editor.UpdatePrefabList(this);
            }
        }

        public bool SaveToNode(XmlNode node, XmlDocument doc) {
            XmlElement prefabs = doc.CreateElement("Prefabs");
            node.AppendChild(prefabs);

            if (contentList != null) {
                foreach (KeyValuePair<string, GameObject> keyValue in contentList) {
                    keyValue.Value.SaveToNode(prefabs, doc);
                }
            }
            return true;
        }

        static public PrefabList LoadFromNode(XmlNode prefabs, Scene scene) {
            PrefabList prefabList = new PrefabList();

            // LoadFromNode
            foreach (XmlNode gameObject in prefabs.ChildNodes) {
                GameObject newGameObject = GameObject.LoadFromNode(gameObject, scene);
                prefabList.AddItem(newGameObject.Name, newGameObject);
            }

            if (Mgr<GameEngine>.Singleton._gameEngineMode == GameEngine.GameEngineMode.MapEditor) {
                Mgr<GameEngine>.Singleton.Editor.UpdatePrefabList(prefabList);
            }

            return prefabList;
        }
    }
}
